package hot150;

// https://leetcode.cn/problems/trapping-rain-water/description/?envType=study-plan-v2&envId=top-interview-150
public class q16 {

    public int trap(int[] height) {
        return method1(height, height.length);
    }

    /**
     * 贪心 + 双指针
     * 1 ms
     * 复杂度O(n)
     */
    public int method1(int[] height, int n) {
        int i = 0, j = n - 1;
        int leftMax = 0, rightMax = 0;
        int sum = 0;
        while (i < j) {
            // 获取左右边界的最高值
            leftMax = Math.max(leftMax, height[i]);
            rightMax = Math.max(rightMax, height[j]);
            // 小的那个需要移动，因为短桶效应，需要找到长的桶
            sum += leftMax < rightMax ? leftMax - height[i++] : rightMax - height[j--];
        }
        return sum;
    }
}
